package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;

	//获取声音播放进度
	@Override
	public BigDecimal getTrackBreakSecond(Long userId, Long trackId) {

		Criteria criteria = Criteria.where("userId").is(userId).and("trackId").is(trackId);
		Query query = new Query(criteria);
//		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		String collectionName = "track_"+userId;
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		if(userListenProcess!=null){
			return userListenProcess.getBreakSecond();
		}
		return new BigDecimal("0");
	}

	//保存或更新播放进度
	@Override
	public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {
		//1 根据userId + trackId 查询
		Criteria criteria = Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId());
		Query query = new Query(criteria);
//		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		String collectionName = "track_"+userId;
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//2 如果可以查询到数据 说明有播放进度 进行更新
		if(userListenProcess!=null){
			userListenProcess.setUpdateTime(new Date());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			mongoTemplate.save(userListenProcess,collectionName);
		}else{
			// 3 如果不能查询到数据 说明是第一次播放 进行保存
			//说明userListenProcess等于null，所以要new
			userListenProcess = new UserListenProcess();
			BeanUtils.copyProperties(userListenProcessVo,userListenProcess);
			//设置id
			userListenProcess.setId(ObjectId.get().toString());
			//设置用户id
			userListenProcess.setUserId(userId);
			//设置是否显示
			userListenProcess.setIsShow(1);
			//创建时间
			userListenProcess.setCreateTime(new Date());
			//更新时间
			userListenProcess.setUpdateTime(new Date());
			mongoTemplate.save(userListenProcess,collectionName);
		}

		// 4 更新声音播放量
		//同一个用户对应同一个声音，24小时以内计算一次播放量
		//使用redis 的setnx+过期时间
		//redis的key是用户id+声音id
		String key = "playnum_"+ userId+userListenProcessVo.getTrackId();
		Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, userListenProcessVo.getTrackId()
				, 24, TimeUnit.HOURS);
		if (ifAbsent){
			//加锁成功 说明是第一次
			//异步方式rabbitMQ更新播放量
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setAlbumId(userListenProcess.getAlbumId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-",""));

			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE,
					JSON.toJSONString(trackStatMqVo));

		}

	}
}
